<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/9/29 20:19
 */

namespace module\chat\front;

use app\library\Interface\TotalInterface;
use think\facade\Db;

class Total implements TotalInterface
{
    public function totals(): array
    {
        return [
            'unlimited' => '自由对话',
            'assistant' => '创作助手对话',
            'visrole'   => '角色对话'
        ];
    }

    public function trends(): array
    {
        return [
            ['title' => '对话走势', 'names' => ['unlimited', 'assistant', 'visrole']]
        ];
    }

    public function unlimited(): int
    {
        return $this->getTotalData('unlimited');
    }

    public function assistant(): int
    {
        return $this->getTotalData('assistant');
    }

    public function visrole(): int
    {
        return $this->getTotalData('visrole');
    }

    protected function getTotalData($key): int
    {
        static $data;
        //获取数据
        if (!$data) {
            $rows = Db::name('chat_message')
                ->where(['received' => 1])
                ->group('object_type') //分组
                ->field('object_type, count(id) as total')
                ->select();
            if ($rows->count()) {
                foreach ($rows as $row) {
                    $data[$row['object_type']] = $row['total'];
                }
            } else {
                $data = [];
            }
        }
        return $data[$key] ?? 0;
    }
}